import React, { useEffect } from 'react';

interface Message {
  id: string;
  content: string;
  sender: 'user' | 'ai';
  timestamp: Date;
  emotionAnalysis?: Record<string, number>;
  isAudio?: boolean;
}

interface ChatMessageListProps {
  messages: Message[];
  aiAvatarComponent: React.ReactNode;
  userAvatarComponent: React.ReactNode;
  playingMessageId: string | null;
  audioStatus: 'idle' | 'loading' | 'playing';
  audioDurations: Record<string, number>;
  playAudioFromHex: (hex: string, id: string) => void;
  getEmotionColor: (msg: Message) => string;
  getWaveformPattern: (id: string) => number[];
  messagesEndRef: React.RefObject<HTMLDivElement>;
  currentResponse: string;
  loading: boolean;
  pendingAiMessageId: string | null;
}

const ChatMessageList: React.FC<ChatMessageListProps> = ({
  messages,
  aiAvatarComponent,
  userAvatarComponent,
  playingMessageId,
  audioStatus,
  audioDurations,
  playAudioFromHex,
  getEmotionColor,
  getWaveformPattern,
  messagesEndRef,
  currentResponse,
  loading,
  pendingAiMessageId,
}) => {
  // 确保头像组件预先渲染，即使它们可能不可见
  useEffect(() => {
    // 这个空的useEffect会确保在组件挂载时就渲染头像组件
    // 这样当消息出现时，头像已经加载完成
  }, [aiAvatarComponent, userAvatarComponent]);

  // 构造最终渲染的消息列表
  let renderMessages: (Message | { id: string; sender: 'ai'; content: string; isLoading?: boolean; isStream?: boolean })[] = [...messages];

  // 如果需要显示 loading 动画（且最后一条不是AI消息），插入 loading 占位消息
  const showLoading = loading && !currentResponse && (messages.length === 0 || messages[messages.length - 1].sender !== 'ai');
  if (showLoading && pendingAiMessageId) {
    renderMessages.push({ id: pendingAiMessageId, sender: 'ai', content: '', isLoading: true });
  }
  // 如果有流式响应，插入流式气泡占位消息
  if (currentResponse && pendingAiMessageId) {
    renderMessages.push({ id: pendingAiMessageId, sender: 'ai', content: currentResponse, isStream: true });
  }
 
  return (
    <div  className="flex-1 overflow-y-auto overscroll-contain space-y-4 touch-auto relative z-1 custom-scrollbar-thin" style={{ WebkitOverflowScrolling: 'touch' }}>
      {/* 预渲染头像（不可见） */}
      <div style={{ position: 'absolute', visibility: 'hidden', pointerEvents: 'none' }}>
        {aiAvatarComponent}
        {userAvatarComponent}
      </div>
      {/* 统一渲染所有消息，包括 loading/流式气泡 */}
      {renderMessages.map((message) => {
        if ((message as any).isLoading) {
          // loading 动画气泡
          return (
            <div key={message.id} className="flex justify-start animate-fadeIn" style={{ animationDelay: '0ms', animationDuration: '150ms' }}>
              <div>{aiAvatarComponent}</div>
              <div className="flex flex-col items-start max-w-[70%]">
                <div
                  className="rounded-lg ml-2 px-4 py-4 animate-fadeIn w-full"
                  style={{ backgroundColor: 'rgb(37,37,37)', animationDelay: '0ms', animationDuration: '150ms', minWidth: 180 }}
                >
                  {/* 自定义 loading 动画 */}
                  <style>{`
                    @keyframes ld4 {
                      0% { opacity: 0; transform: scale(0.3); background: #59CD90; }
                      25% { opacity: 1; transform: scale(1.8); background: #0072BB; }
                      50% { opacity: 0; transform: scale(0.3); background: #FE4A49; }
                      75% { opacity: 1; transform: scale(1.8); background: #FED766; }
                      100% { opacity: 0; }
                    }
                  `}</style>
                  <div className="loader" style={{ width: '100%', display: 'flex', justifyContent: 'flex-start' }}>
                    <div id="ld4" style={{ display: 'flex', width: 80, justifyContent: 'space-between' }}>
                      <div style={{ height: 12, width: 12, borderRadius: '50%', background: '#D91E36', animation: 'ld4 3s linear infinite 0s' }}></div>
                      <div style={{ height: 12, width: 12, borderRadius: '50%', background: '#D91E36', animation: 'ld4 3s linear infinite 0.15s' }}></div>
                      <div style={{ height: 12, width: 12, borderRadius: '50%', background: '#D91E36', animation: 'ld4 3s linear infinite 0.3s' }}></div>
                      <div style={{ height: 12, width: 12, borderRadius: '50%', background: '#D91E36', animation: 'ld4 3s linear infinite 0.45s' }}></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          );
        }
        if ((message as any).isStream) {
          // 流式响应气泡
          return (
            <div key={message.id} className="flex justify-start animate-fadeIn" style={{ animationDelay: '0ms', animationDuration: '150ms' }}>
              <div>{aiAvatarComponent}</div>
              <div className="flex flex-col items-start max-w-[70%]">
                <div
                  className="rounded-lg ml-2 px-4 py-4 text-[rgb(209,209,209)] animate-fadeIn w-full"
                  style={{ backgroundColor: 'rgb(37,37,37)', animationDelay: '0ms', animationDuration: '150ms' }}
                >
                  <p>{currentResponse}</p>
                </div>
              </div>
            </div>
          );
        }
        // 普通消息
        return (
          <div key={message.id} className="flex justify-start">
            <div>{message.sender === 'ai' ? aiAvatarComponent : userAvatarComponent}</div>
            <div className="ml-2 p-3 rounded-lg bg-gray-700 text-white">
              {message.content}
            </div>
          </div>
        );
      })}
      <div ref={messagesEndRef} id="messagesEndRef" />
    </div>
  );
};

export default ChatMessageList; 